package com.lxl.settings.controller;



import com.lxl.commons.contants.BaseServlet;
import com.lxl.commons.contants.Contants;
import com.lxl.commons.domain.ReturnObject;
import com.lxl.commons.utils.Md5;
import com.lxl.commons.utils.VerifyCodeUtil;
import com.lxl.settings.entity.User;
import com.lxl.settings.service.StaffService;
import com.lxl.settings.service.UserService;
import com.lxl.settings.service.impl.StaffServiceImpl;
import com.lxl.settings.service.impl.UserServiceImpl;
import com.lxl.workbench.entity.Administrator;
import com.lxl.workbench.entity.CategoryStaff;
import com.lxl.workbench.entity.CommonStaff;
import com.lxl.workbench.entity.Curator;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 北上寻海
 */

@WebServlet({"/verifyCode","/login"})
public class UserServlet extends BaseServlet {

    /**
     * 以下分别是user、commonStaff、curator的service对象
     */
    UserService userService = new UserServiceImpl();
    StaffService staffService = new StaffServiceImpl();

    /**
     * 生成验证码图片的方法
     * @param request 请求域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void  getVerifyCode(HttpServletRequest request, HttpServletResponse response) throws   IOException {
        //将验证码存入session会话域
        String verifyCode =  VerifyCodeUtil.getVerifyCode(4);
        HttpSession session = request.getSession();
        session.setAttribute("verifyCode",verifyCode);
        //将验证码放进图片，流输出图片
        response.setContentType("image/jpeg");
        ServletOutputStream os = response.getOutputStream();
        VerifyCodeUtil.outputImage(os,verifyCode);
    }

    /**
     * 登录验证并根据权限转发到对应的页面
     * @param request 请求域
     * @param response 响应域
     * @throws IOException io异常
     * @throws ServletException servlet异常
     */
    public void userLogin (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //设置响应信息的对象
        ReturnObject returnObject = new ReturnObject();
        //获取用户填写的用户名和密码作登录验证
        String username = request.getParameter("username");
        String password = Md5.md5(request.getParameter("password"));
        String loginInFree = request.getParameter("loginInFree");

        //拿出存在session会话域的验证码和前端页面发过来的验证码作比较
        HttpSession session = request.getSession();
        String verifyCode1 = (String) session.getAttribute("verifyCode");
        String verifyCode2 = request.getParameter("verifyCode");

        List<User> userList = new ArrayList<>();
        //根据权限判断是哪一类用户，转发到对应的工作页面
        String permissions = null;
        if (verifyCode1.equalsIgnoreCase(verifyCode2)) {
                try {
                     userList= userService.queryUser(username, password);
                } catch (SQLException e) {
                    e.printStackTrace();
                    returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                    returnObject.setMessage("用户名或密码错误");
                    request.setAttribute("returnObject",returnObject);
                    request.getRequestDispatcher("/index.jsp").forward(request,response);
                }
                if (userList != null&&!userList.isEmpty()) {
                     User user = userList.get(0);
                     String id = user.getId();
                     //验证是哪类职工,获取他们的权限
                     try {
                        List<CommonStaff> commonStaffList = staffService.queryCommonStaffById(id);
                        if(commonStaffList==null||commonStaffList.isEmpty()){
                            List<Curator> curatorList = staffService.queryCuratorById(id);
                            if(curatorList==null||curatorList.isEmpty()){
                                List<CategoryStaff> categoryStaffList = staffService.queryCategoryStaffById(id);
                                if(categoryStaffList==null||categoryStaffList.isEmpty()){
                                    List<Administrator> administratorList = staffService.queryAdministratorById(id);
                                    permissions = administratorList.get(0).getPermissions();
                                }else {
                                    permissions=categoryStaffList.get(0).getPermissions();
                                    String manageType = categoryStaffList.get(0).getManageType();
                                    request.setAttribute("manageType",manageType);
                                }
                            }else {
                                permissions=curatorList.get(0).getPermissions();
                            }
                        }else {
                            permissions = commonStaffList.get(0).getPermissions();
                        }
                     }catch (SQLException e){
                         e.printStackTrace();
                     }

                     //到这里登录验证已经通过了 如果选了免登录，写cookie给浏览器
                    if(Contants.LOGIN_IN_FREE.equals(loginInFree)) {
                        Cookie cookie1 = new Cookie(Contants.USERNAME_COOKIE, username);
                        Cookie cookie2 = new Cookie(Contants.PASSWORD_COOKIE, password);
                        cookie1.setMaxAge(3600 * 24 * 7);
                        cookie2.setMaxAge(3600 * 24 * 7);
                        cookie1.setPath(request.getContextPath());
                        cookie2.setPath(request.getContextPath());
                        response.addCookie(cookie1);
                        response.addCookie(cookie2);
                    }
                    //已经登录信息在这里存进session域，过滤器验证会用到
                    session.setAttribute(Contants.SESSION_USER, user);

                    //根据权限跳转到不同的工作页面
                     if(Contants.CURATOR_PERMISSIONS.equals(permissions)){
                         //馆长
                         response.sendRedirect("/curatorWork.jsp");

                     }else if(Contants.COMMON_STAFF_PERMISSIONS.equals(permissions)){
                         //普通员工
                         response.sendRedirect("/commonStaffWork.jsp");

                     }else if(Contants.CATEGORY_STAFF_PERMISSIONS.equals(permissions)){
                         //书目管理员
                         request.getRequestDispatcher("/categoryStaffWork.jsp").forward(request,response);

                     }else if(Contants.ADMINISTRATOR.equals(permissions)){
                         //总管理员
                         response.sendRedirect("/administratorWork.jsp");
                     }
            }else {
                    //登录失败，请求转发
                    returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                    returnObject.setMessage("用户名或密码错误");
                    request.setAttribute("returnObject",returnObject);
                    request.getRequestDispatcher("/index.jsp").forward(request,response);
                }
        }else {
                 //登录失败，请求转发
                 returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                 returnObject.setMessage("验证码错误");
                 request.setAttribute("returnObject",returnObject);
                 request.getRequestDispatcher("/index.jsp").forward(request,response);
            }
    }

    @Override
    public void destroy() {
        super.destroy();
    }
}
